package com.ts.proj.json;


import com.ts.base.controller.BaseController;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.proj.entity.ErrorprojectEntity;
import com.ts.proj.entity.FileEntity;
import com.ts.proj.entity.excelEntity.FileEntityExcel;
import com.ts.proj.entity.SystemUserEntity;
import com.ts.proj.service.ErrorprojectDetailService;
import com.ts.proj.service.ErrorprojectService;
import com.ts.proj.service.FileService;
import com.ts.common.constant.ConsoleConstant;
import com.ts.util.PageData;
import com.ts.util.StringsUtil;
import com.ts.util.DateUtil;
import com.ts.util.EasyPoiUtil;
import com.ts.util.EntityAttributeUtil;
import com.ts.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;



import javax.servlet.http.HttpSession;
import com.ts.proj.entity.SystemUserEntity;
import com.ts.util.JsonUtils;
import com.ts.common.constant.ConsoleConstant;

//说明 字符串：File，作为替换字符串 LOWERFile

@RestController
public class FileJson extends BaseController{

    @Autowired
    private FileService fileService;

    @Autowired
    private ErrorprojectService errorprojectService;

    @Value("${upload.location-pre}")
    private String locaionPre ;

    @Value("${upload.split}")
    private String split;

    /**
     * 显示list
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/file-list/{page}/{size}")
    public Map<String,Object> fileList(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
	
		HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
	
        PageData pageData = this.getPageData();

        //文件名查询
        if(null!=pageData.get("fileName")&&!"".equals(pageData.get("fileName").toString())){
            pageData.put("fileName", pageData.get("fileName").toString());
        }
        //项目名
        if(null!=pageData.get("uuid")&&!"".equals(pageData.get("uuid").toString())){
            pageData.put("uuid", pageData.get("uuid").toString());
        }
        //项目状态
        if(null!=pageData.get("state")&&!"".equals(pageData.get("state").toString())){
            pageData.put("state", pageData.get("state").toString());
        }
        //错误详情id
        if(null!=pageData.get("errorDetailId")&&!"".equals(pageData.get("errorDetailId").toString())){
            pageData.put("errorDetailId", pageData.get("errorDetailId").toString());
        }
        //项目id
        if(null!=pageData.get("projId")&&!"".equals(pageData.get("projId").toString())){
            pageData.put("projId", pageData.get("projId").toString());
        }
        if(null!=pageData.get("docType")&&!"".equals(pageData.get("docType").toString())){
            pageData.put("docType", pageData.get("docType").toString());
        }
		//用户权限
        if(user.getPowerLevel().equals("0")){
            pageData.put("userId", user.getId());
        }
        pageData.put("belongTo", user.getBelongTo());
		
        long count = fileService.count(pageData);
        List<FileEntity> files = fileService.findAll(pageData,page-1,size);
        pageData.put("total",count);
        pageData.put("rows", files);
        return pageData;
    }

    /**
     * 常量增删改
     * @return
     */
    @RequestMapping(value = "/file-ins-upd-del/{id}")
    public Object logCreateUpdate(@PathVariable("id") String id){ 
	
		FileEntity file = fileService.findById(Integer.valueOf(id));
        PageData pageData = this.getPageData();

        List<String> strings = EntityAttributeUtil.entityAttribute(FileEntity.class);
		 SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        for(String attr :strings){
            //字段信息维护
            if(null!=pageData.get(attr)&&!"".equals(pageData.get(attr).toString())){
                //目前只能手动添加，这里添加所需要增加和修改的字段
                try {
                    Method[] methods = FileEntity.class.getDeclaredMethods();
                    for(int i=0;i<methods.length;i++){
                        Method method = methods[i];
                        Class<?>[] returnType = method.getParameterTypes();
                        if(method.getName().contains(StringsUtil.upperCase(attr))&&!method.getName().contains("get")){
                            if (returnType[0].getName().equals("java.lang.Integer")){
                                method.invoke(file, Integer.valueOf(pageData.getString(attr)));
                            }
                            else{
                                method.invoke(file, pageData.getString(attr));
                            }
                        }
						if(method.getName().equals("setUserId")){
                            file.setUserId(systemUserEntity.getId());
                        }
                        if(method.getName().equals("setBelongTo")){
                            file.setBelongTo(systemUserEntity.getBelongTo());
                        }
						if(method.getName().equals("setPowerLevel")){
                            file.setPowerLevel(systemUserEntity.getPowerLevel());
                        }

                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }  catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        //删除
        if(null!=pageData.get("deleteFlag")&&!"".equals(pageData.get("deleteFlag").toString())){
            String path = locaionPre;
            path += file.getUuid() + split + file.getState()
                    + split + file.getState() + "_" + file.getProjName();
            File localFile = new File(path);
            localFile.delete();
        }
        fileService.save(file);
        return null;
    } 
	@RequestMapping("/file-download")
    public void export(HttpServletResponse response){
        PageData param = new PageData();
        param.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<FileEntity> entitys = fileService.findAll(param);
        List<FileEntityExcel> excelEntities = new ArrayList<>();
        for(FileEntity tempEntity :entitys){            
            FileEntityExcel excel = new CopyObjectEntity2EntityExcel<FileEntityExcel, FileEntity>().copy(FileEntityExcel.class,FileEntity.class,tempEntity);
            excelEntities.add(excel);
        }
        EasyPoiUtil.exportExcel(excelEntities,"","",FileEntityExcel.class, DateUtil.getID()+".xls",response);
    }

    @RequestMapping("/project-has-file/{uuid}/{state}")
    public boolean projectHasFiles(@PathVariable("uuid") String uuid,@PathVariable("state") String state){
        PageData pd = new PageData();
        pd.put("deleteFlag", "N");
        pd.put("uuid", uuid);
        pd.put("state", state);
        List<FileEntity> all = fileService.findAll(pd);
        if(all.size()==0){
            return false;
        }
        return true;
    }

    @RequestMapping("/project-touhou-has-file/{uuid}/{docType}")
    public boolean projectTHouHasFiles(@PathVariable("uuid") String uuid,@PathVariable("docType") String docType){
        PageData pd = new PageData();
        pd.put("deleteFlag", "N");
        pd.put("projId", uuid);
        pd.put("docType", docType);
        List<FileEntity> all = fileService.findAll(pd);
        if(all.size()==0){
            return false;
        }
        return true;
    }



    @RequestMapping("/project-juece-has-file/{uuid}/{docType}")
    public boolean projectJueceHasFiles(@PathVariable("uuid") String uuid,@PathVariable("docType") String docType){
        PageData pd = new PageData();
        pd.put("deleteFlag", "N");
        pd.put("projId", uuid);
        pd.put("docType", docType);
        List<FileEntity> all = fileService.findAll(pd);
        if(all.size()==0){
            return false;
        }
        return true;
    }

    @RequestMapping("/errorproject-has-file/{uuid}/{state}")
    public boolean errorprojectHasFiles(@PathVariable("uuid") String uuid,@PathVariable("state") String state){
        PageData pd = new PageData();
        pd.put("deleteFlag", "N");
        pd.put("errorDetailId", uuid);
        pd.put("state", state);
        List<FileEntity> all = fileService.findAll(pd);
        if(all.size()==0){
            return false;
        }
        return true;
    }




    @RequestMapping("/file-location/{id}")
    public String fileLocation(@PathVariable("id") String id){
        FileEntity byId = fileService.findById(Integer.valueOf(id));
        String fileName = byId.getFileName();
        String uuid = byId.getUuid();
        String state = fileName.substring(0, 2);
        String url = "/files/" + uuid + "/" + state + "/" + fileName;
        return url;
    }
}